using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;

namespace LanguageConfigurationSolution
{
    class LanguageConfigurationExpressionBuilderFeatureReceiver : SPFeatureReceiver
    {
        private void ApplyWebConfigModificationsToFarm(SPWebApplication webApp)
        {
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry( this.GetType().FullName , string.Format("Exception occured running the FeatureReceiver when ApplyWebConfigModifications was called.{0}If you give WSS_WPG user account full permission to the config folder the error will disappear!{0}{1}",Environment.NewLine, ex.ToString() ) , EventLogEntryType.Error );
                });
                throw;
            }
        }

        private string Owner
        {
            get
            {
                return this.GetType().FullName + ", " + this.GetType().Assembly.FullName;
            }
        }

        private const string LANGUAGECONFIGURATIONPREFIX = "LanguageConfiguration";

        private SPWebConfigModification AddExpressionBuilder_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification(string.Format("add[@expressionPrefix='{0}']",LANGUAGECONFIGURATIONPREFIX), "configuration/system.web/compilation/expressionBuilders");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                modification.Value = string.Format("<add expressionPrefix=\"{0}\" type=\"{1},{2}\"/>",LANGUAGECONFIGURATIONPREFIX, typeof(LanguageExpressionBuilder).FullName, typeof(LanguageExpressionBuilder).Assembly.FullName) ;
                modification.Owner = Owner;
                return modification;
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp= properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            webapp.WebConfigModifications.Add(AddExpressionBuilder_modification);

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            ApplyWebConfigModificationsToFarm(webapp);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            for (int idx = webapp.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                SPWebConfigModification conmod = webapp.WebConfigModifications[idx];
                if (string.Compare(conmod.Owner, Owner, true) == 0)
                {
                    webapp.WebConfigModifications.RemoveAt(idx);
                }
            }

            webapp.Update(); // Important
            ApplyWebConfigModificationsToFarm(webapp);

        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
